import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import vueDevTools from 'vite-plugin-vue-devtools'
import postCssPxToRem from 'postcss-pxtorem'

export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd())

  // 调试输出，确认环境变量值
  console.log('当前环境模式:', mode)
  console.log('VITE_API_BASE_URL:', env.VITE_API_BASE_URL)

  // 检查 target 是否合法
  const target = env.VITE_API_BASE_URL
  if (!target || !/^https?:\/\//.test(target)) {
    throw new Error(`[Vite 代理配置错误] 无效的 VITE_API_BASE_URL: ${target}`)
  }

  return {
    plugins: [
      vue(),
      vueDevTools(),
      AutoImport({
        resolvers: [VantResolver()],
      }),
      // 自动导入的插件
      Components({
        dts: false,
        resolvers: [VantResolver({ importStyle: true })],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      open: true,
      port: 5173,
      proxy: {
        '/api': {
          target: target,
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 16,
            propList: ['*'],
            selectorBlackList: ['.van'], // 过滤掉vant
            exclude: /node_modules/i,
          }),
        ],
      },
    },
  }
})
